import os

import pyperclip
from prompt_toolkit import PromptSession
from prompt_toolkit.completion.fuzzy_completer import FuzzyWordCompleter
from prompt_toolkit.key_binding import KeyBindings
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import SqlLexer


def ctrl_c_handler(event):
    pass


def get_snippet_names():
    work_dir = os.path.dirname(__file__)
    snippet_dir = os.path.join(work_dir, "snippets")
    file_names = os.listdir(snippet_dir)
    snippets = list()
    for file_name in file_names:
        snippets.append(file_name)
    print("find {} snippets".format(len(snippets)))
    return snippets


def get_snippet(snippet_name):
    work_dir = os.path.dirname(__file__)
    snippet_file = os.path.join(work_dir, "snippets", snippet_name)
    if not os.path.exists(snippet_file):
        return "sorry, please choose the right snippet"
    with open(snippet_file, 'r') as file:
        return file.read()


def get_snippet_completer():
    snippet_names = get_snippet_names()
    fuzzy_completer = FuzzyWordCompleter(snippet_names)
    return fuzzy_completer


def loop_suggest():
    snippet_completer = get_snippet_completer()
    key_bindings = KeyBindings()
    # 注册ctrl+c事件,避免ctrl+c停止服务
    key_bindings.add('c-c')(ctrl_c_handler)
    prompt_session = PromptSession(message='SQL > ', completer=snippet_completer, key_bindings=key_bindings)
    while True:
        user_input = prompt_session.prompt().strip()
        if user_input == "":
            continue
        if user_input == "exit":
            print("bye")
            exit(1)
        snippet_data = get_snippet(snippet_name=user_input)
        # 复制到剪切板
        pyperclip.copy(snippet_data)
        # 高亮显示
        highlight_data = highlight(snippet_data, SqlLexer(), TerminalFormatter())
        print("=" * 70)
        print(highlight_data)
        print("")
    pass


def main():
    loop_suggest()


if __name__ == '__main__':
    main()
